package cn.itcast.task;

import cn.itcast.lock.RedisLockFactory;
import cn.itcast.lock.SimpleRedisLock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author 虎哥
 */
@Slf4j
@Component
public class HelloTask {

    @Autowired
    private RedisLockFactory lockFactory;

    @Scheduled(cron = "0/10 * * * * ?")
    public synchronized void job() throws InterruptedException {
        // 获取锁对象
        SimpleRedisLock lock = lockFactory.getSimpleRedisLock("lock");
        // 尝试获取锁
        boolean isLock = lock.tryLock(20, TimeUnit.SECONDS);
        if(!isLock){
            // 获取锁失败
            log.error("获取锁失败，定时任务终止！");
            return;
        }
        try {
            // 获取锁成功
            log.info("获取锁成功，开始执行任务。");
            Thread.sleep(500);
        } finally {
            // 释放锁
            lock.unlock();
            log.warn("定时任务结束，释放锁");
        }
    }
}
